package com.sunrise.xdoc.view.contact;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.sunrise.xdoc.entity.contact.KhachHang;
import com.sunrise.xdoc.entity.contact.LoaiKhachHang;
import com.sunrise.xdoc.event.EventData;
import com.sunrise.xdoc.event.ListenerMethod;
import com.sunrise.xdoc.view.AbstractView;

@ManagedBean
@SessionScoped
public class KhachHangView extends AbstractView<KhachHang> {
	private static final long serialVersionUID = 6113130592162546486L;

	private List<LoaiKhachHang> loaiKHs = new ArrayList<>();

	@Override
	@PostConstruct
	protected void init() {
		super.init();
		loaiKHs = getDaoHelper().getDao(LoaiKhachHang.class).loadAll();
	}

	@ListenerMethod(acceptedEvents = { "saveOrUpdateLoaiKhachHang", "deleteLoaiKhachHang" })
	public void processEvents(EventData e, String eventName) {
		init();
	}

	public Long getSelectedLoaiKhachHangId() {
		if (getEditedEntity() != null && getEditedEntity().getLoai() != null) {
			return getEditedEntity().getLoai().getId();
		}
		return null;
	}

	public void setSelectedLoaiKhachHangId(Long selectedLoaiKhachHangId) {
		for (LoaiKhachHang lkh : loaiKHs) {
			if (selectedLoaiKhachHangId.equals(lkh.getId())) {
				getEditedEntity().setLoai(lkh);
				return;
			}
		}
		getEditedEntity().setLoai(null);
	}

	@Override
	protected String getDataModelBeanName() {
		return "khachHangDataModel";
	}

	@Override
	protected String getDetailPanelViewId() {
		return "khachHangDialogId";
	}

	public List<LoaiKhachHang> getLoaiKHs() {
		return loaiKHs;
	}

}
